<template>
  <div class="create-wrapper">
    <el-card>
      <div slot="header" class="clearfix">
        <span>商品基本信息</span>
        <el-button style="float: right; padding: 3px 0" type="text"
          >收起</el-button
        >
      </div>

      <div style="margin-bottom: 10px">
        <el-form :model="form" label-width="auto" style="max-width: 600px">
          <el-form-item label="商品名称">
            <el-input v-model="form.name" />
          </el-form-item>

          <el-form-item label="商品分类" style="max-width: 600px">
            <el-tree-select
              v-model="form.category"
              :data="secondList"
              style="width: 240px"
            >
              <!-- <template #default="{ data: { name } }"> {{ name }}</template> -->
            </el-tree-select>
            <!-- <el-select v-model="form.category" placeholder="请选择分类">
              <el-option v-for="item in secondList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select> -->
          </el-form-item>
          <el-form-item label="商品描述">
            <el-input v-model="form.desc" type="textarea" />
          </el-form-item>

          <el-form-item label="商品详情">
            <el-input v-model="form.detail" type="textarea" />
          </el-form-item>

          <el-form-item label="商品图片">
            <ImageUpload v-model="form.images" />
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card>
      <div slot="header" class="clearfix">
        <span>商品规格</span>
        <el-button style="float: right; padding: 3px 0" type="text"
          >收起</el-button
        >
      </div>

      <div style="margin-bottom: 10px">
        <el-popover width="370" placement="bottom" trigger="click">
          <div>
            <el-input
              v-model="specName"
              ref="InpuSpecRef"
              @keyup.enter="addSpecName()"
              placeholder="请输入规格名称"
            >
              <template #append>
                <el-button type="primary" size="small" @click="addSpecName()"
                  >添加规格名</el-button
                >
              </template>
            </el-input>
          </div>

          <template #reference>
            <el-button type="primary">+添加规格</el-button>
          </template>
        </el-popover>
      </div>
      <div>
        <div v-if="specData.specList.length > 0">
          <div
            v-for="(item, index) in specData.specList"
            :key="index"
            class="spec-section"
          >
            <el-divider>
              <div>{{ item.label }}</div>
            </el-divider>
            <div>
              <div style="display: flex; align-items: center">
                <el-tag>{{ item.label }}</el-tag>
                <div style="margin-left: 15px" @click="onDeletSpec(index)">
                  <el-button type="danger" size="small" :icon="Delete" />
                </div>
              </div>
            </div>
            <div style="display: flex">
              <div v-for="(tagNmae, tagIndex) in item.tags" :key="tagIndex">
                <el-tag
                  size="small"
                  @close="onDeletSpecValue(index, tagIndex)"
                  closable
                  style="margin: 0 10px 10px 0"
                  >{{ tagNmae }}</el-tag
                >
              </div>
              <div style="margin: 0 10px 10px 0">
                <el-input
                  v-if="inputIndex === index && inputVisible"
                  size="small"
                  ref="InputRef"
                  v-model="inputTags"
                  @keyup.enter="handleInputConfirm(index, item.label)"
                  @blur="handleInputConfirm(index, item.label)"
                  placeholder="请输入规格值"
                />
                <el-button v-else size="small" @click="onClilkInput(index)"
                  >添加规格值</el-button
                >
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="add-spec-wrapper">
        <el-button type="primary" @click="addSpec">新增一行</el-button>
      </div>
      <el-table :data="submitList" border>
        <!-- <el-table-column
          v-for="(item, index) in specData.specList"
          :label="item.label"
          :key="index"
        >
          <template #default="{ row, column }">
            <span>{{ row[column.label] }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="规格">
          <template #default="{ $index }">
            <el-input
              v-model="submitList[$index]['sku']"
              @focus="showSpec($index)"
            />
          </template>
        </el-table-column>

        <el-table-column
          v-for="(item, index) in tableHader"
          :label="item.label"
          :key="index"
        >
          <template #default="{ $index }">
            <el-input-number
              v-if="item.label === '价格'"
              v-model="submitList[$index][item.key]"
              :precision="2"
              size="small"
            />
            <el-input-number
              v-else
              v-model="submitList[$index][item.key]"
              size="small"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template #default="scope">
            <!-- <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
              >Edit</el-button
            > -->
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div class="footer">
      <div class="footer-wrapper">
        <el-button v-if="route.query.id" type="primary" @click="onSubmit"
          >更新商品</el-button
        >
        <el-button v-else type="primary" @click="onSubmit">添加商品</el-button>
        <el-button @click="goBack">取消</el-button>
      </div>
    </div>

    <el-dialog
      v-model="dialogSpecVisible"
      title="规格选择"
      @close="closeDialog"
      width="600px"
      :show-close="false"
    >
      <SpecSelect :data="specData.specList" @specConfirm="specConfirm" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { ref, reactive, nextTick, onMounted } from "vue";
import { Delete } from "@element-plus/icons-vue";
import ImageUpload from "./components/image-upload.vue";
import SpecSelect from "./components/specs.vue";
import { useProductStoreHook } from "@/store/modules/product";
import { useCategoryStoreHook } from "@/store/modules/category";
import { useRoute, useRouter } from "vue-router";
import { buildTree } from "@/utils/tree";

const route = useRoute();
const router = useRouter();

const form = reactive({
  name: "",
  desc: "",
  detail: "",
  category: "",
  attribute_list: [],
  images: []
});

// ------------变量----------------
const currentIndex = ref("");
const secondList = ref([]);

const showSpec = index => {
  dialogSpecVisible.value = true;
  currentIndex.value = index;
};

const closeDialog = () => {
  dialogSpecVisible.value = false;
};

const specConfirm = sku => {
  if (sku) {
    submitList.value[currentIndex.value].sku = sku;
  }
  dialogSpecVisible.value = false;
};

const addSpec = () => {
  submitList.value.push({
    sku: "",
    price: 0,
    stock: 0
  });
};

const dialogSpecVisible = ref(false);
const specName = ref(""), //规格名
  inputTags = ref(""), // 规格值
  inputVisible = ref(false),
  inputIndex = ref(0),
  submitList = ref([]),
  specData = reactive({
    specList: [],
    skuValue: {}
  });

const InputRef = ref(null);
const InpuSpecRef = ref(null);
const tableHader = [
  { label: "价格", key: "price" },
  { label: "库存", key: "stock" }
];
// ------------变量----------------

// ------------生命周期----------------
// watch(submitList, _newValue => {}, { deep: true });
// ------------生命周期----------------

onMounted(() => {
  if (route.query.id) {
    useProductStoreHook()
      // .getProductInfo("7971b655-3c19-43ff-8aae-31459c0e1f00")
      .getProductInfo(route.query.id)
      .then(res => {
        if (res.code === 200) {
          form.name = res.data.name;
          form.detail = res.data.detail;
          form.desc = res.data.desc;
          form.category = res.data.category;
          form.images = res.data.images;
          const attribute_list = res.data.attribute_list[0];
          const specList = Object.keys(attribute_list).map(key => {
            return { label: key, tags: attribute_list[key] };
          });
          specData.specList = specList;
          specData.skuValue = attribute_list;
          submitList.value = res.data.specs;
        }
      })
      .catch(() => {
        // loading.value = false;
      });
  }

  // 获取商品二级分类列表
  useCategoryStoreHook()
    .getCategoryList()
    .then(res => {
      if (res.code === 200) {
        console.log(res);
        secondList.value = buildTree(res.data);
        // secondList.value = res.data;
      }
    });
});

// -----------function-----------------

function addSpecName() {
  if (specName.value) {
    specData.specList.push({ label: specName.value, tags: [] });
    specName.value = "";
  } else {
    ElMessage.warning("请输入规格名称");
  }
}
function handleInputConfirm(index, label) {
  if (inputTags.value) {
    //找到并吧输入值push到tags里面
    specData.specList[index].tags.push(inputTags.value);
    if (!specData.skuValue[label]) specData.skuValue[label] = [inputTags.value];
    else specData.skuValue[label].push(inputTags.value);
  }
  inputTags.value = "";
  nextTick(() => {
    inputVisible.value = !inputVisible.value;
  });
}
function onClilkInput(index) {
  inputIndex.value = index; // 获取输入框下标
  inputVisible.value = !inputVisible.value; // 显示输入框
  nextTick(() => {
    InputRef.value[0]?.input?.focus();
  });
}
function onDeletSpec(index) {
  //删除规格
  delete specData.skuValue[specData.specList[index].label]; //找到相对于的名称，然后删除skuValue相对于的值
  specData.specList.splice(index, 1); // 同时删除展示的标签
}
function onDeletSpecValue(index, tagIndex) {
  //删除规格值
  specData.skuValue[specData.specList[index].label].splice(tagIndex, 1); //删除tags里面的其中一个值
  specData.specList[index].tags.splice(tagIndex, 1); // 规格值
}

const handleDelete = index => {
  submitList.value.splice(index, 1); // 同时删除展示的标签
};

const onSubmit = () => {
  form.attribute_list = specData.skuValue;
  const params = {
    product: form,
    specs: submitList.value
  };
  if (route.query.id) {
    useProductStoreHook()
      .updateProductInfo(route.query.id, params)
      .then(res => {
        if (res.code === 200) {
          console.log(res);
          router.replace("/product/list");
        }
      });
  } else {
    useProductStoreHook()
      .addProductInfo(params)
      .then(res => {
        if (res.code === 200) {
          console.log(res);
          router.replace("/product/list");
        }
      });
  }
};
const goBack = () => {
  router.replace("/product/list");
};
</script>

<style lang="css" scoped>
.add-spec-wrapper {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.create-wrapper {
  padding: 0px;
  overflow-y: auto;
}

.footer-wrapper {
  width: 160px;
  margin: 0 auto;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}

.spec-section {
  border-bottom: 1px #ccc;
}

:deep(.el-card) {
  margin-bottom: 10px;
}

:deep(.el-divider--horizontal) {
  margin: 8px 0;
}

.footer {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-evenly;
}
</style>
